package org.xq.mq.config;

import org.xq.mq.listener.ChannelBBCReceiver;
import org.xq.mq.listener.ChannelCCTVReceiver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

@Configuration
public class RedisChannelConfig {
    // 使用Jackson2JsonRedisSerialize 替换默认序列化
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);


    /**
     * 消息监听器适配器，绑定消息处理器
     *
     * @return
     */
    @Bean
    MessageListenerAdapter cctvAdapter() {
        return new MessageListenerAdapter(
                new ChannelCCTVReceiver(),
                "receiveMessage");
    }

    /**
     * 消息监听器适配器，绑定消息处理器
     *
     * @return
     */
    @Bean
    MessageListenerAdapter bbcAdapter() {
        return new MessageListenerAdapter(
                new ChannelBBCReceiver(),
                "receiveMessage"
        );
    }

    /**
     * 添加消息监听器
     * 订阅-发布
     *
     * 可以传入多个 MessageListenerAdapter
     */
    @Bean
    RedisMessageListenerContainer redisMessageListenerContainer(
            RedisConnectionFactory connectionFactory,
            MessageListenerAdapter cctvAdapter,
            MessageListenerAdapter bbcAdapter) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        // 监听所有库的key过期事件
         container.setConnectionFactory(connectionFactory);
//        container.setTopicSerializer(jackson2JsonRedisSerializer);
        // 可以添加多个 messageListener，配置不同的通道
         container.addMessageListener(cctvAdapter, new PatternTopic("topic_cctv_news"));
         container.addMessageListener(bbcAdapter, new PatternTopic("topic_bbc_news"));
        return container;
    }

}
